import Vue from 'vue'
import Router from 'vue-router'

import login from '@/page/login/login'
import layout from '@/page/layout/index'
import default1 from '@/page/index/default'
import screen from '@/page/views/visual-screen'

//获取组件的方法
const _import = require('./_import_' + process.env.NODE_ENV)

//首页
const index = () => import('@/page/index/index')

Vue.use(Router)


/**
 * hidden = 是否隐藏解点
 * alone = 是否是单节点 如果是单节点将使用children下的[0]为路由
 */
const defaultRouter = [{
  path: '/',
  redirect: '/login',
  hidden: true
},
// 默认页
{
  path: '/default',
  name: 'default',
  component: default1,
  hidden: true
},

// 登录页
{
  path: '/login',
  name: 'Login',
  component: login,
  hidden: true
},
{
  path: '/index',
  component: layout,
  name: '首页',
  icon: 'el-icon-s-home',
  alone: true,
  children: [{
    path: '/index',
    component: index,
    name: '首页',
    icon: 'el-icon-s-home',
    children: []
  }]
},
// 大屏页
{
  path: '/screen',
  name: '大屏',
  component: screen,
  hidden: true
},
]

//因为后台传过来的component是字符串,并没有导入组件,所有遍历JSON导入组件
function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  let l = JSON.parse(JSON.stringify(asyncRouterMap))
  return l.filter(route => {
    if (route.component) {
      route.component = _import(route.component)
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export default new Router({
  routes: defaultRouter
})
export {
  defaultRouter,
  filterAsyncRouter
}


/**
 * 重写路由的push方法
 */
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}
